<template>
  <a-card :bordered="false">
    <div class="card-title">{{ $route.meta.title }}</div>
    <a-spin :spinning="isLoading">
      <a-form :form="form" @submit="handleSubmit">
        <a-form-item label="姓名" :label-col="{ span: labelCol.span }" :wrapper-col="{ span: wrapperCol.span }">
          <a-input type="text" placeholder="请输入姓名" v-decorator="['name', { rules: [{ required: true, message: '请输入姓名' }] }]"/>
        </a-form-item>
        <a-form-item label="电话" :label-col="{ span: labelCol.span }" :wrapper-col="{ span: wrapperCol.span }">
          <a-input type="number" placeholder="请输入电话" v-decorator="['mobile', { rules: [{ required: true, message: '请输入电话' }] }]"/>
        </a-form-item>
        <a-form-item label="身份证号" :label-col="{ span: labelCol.span }" :wrapper-col="{ span: wrapperCol.span }">
          <a-input type="number" placeholder="请输入身份证号" v-decorator="['idCard', { rules: [{ required: true, message: '请输入身份证号' }] }]"/>
        </a-form-item>
        <a-form-item label="生日" :label-col="{ span: labelCol.span }" :wrapper-col="{ span: wrapperCol.span }">
          <a-date-picker v-decorator="['birthday', { rules: [{ required: true, message: '请输入生日' }] }]"/>
        </a-form-item>
        <a-form-item label="性别" :label-col="{ span: labelCol.span }" :wrapper-col="{ span: wrapperCol.span }">
          <a-select placeholder="请选择性别" v-decorator="['sex', { rules: [{ required: true, message: '请选择性别' }] }]">
            <a-select-option value="1">
              男
            </a-select-option>
            <a-select-option value="2">
              女
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="年龄" :label-col="{ span: labelCol.span }" :wrapper-col="{ span: wrapperCol.span }">
          <a-input type="number" placeholder="请输入年龄" v-decorator="['age', { rules: [{ required: true, message: '请输入年龄' }] }]"/>
        </a-form-item>
        <a-form-item label="选择地区" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <SelectRegion
            placeholder="请选择省市区"
            v-decorator="['address', {rules: [{required: true, message: '请选择省市区'}]}]"
          />
        </a-form-item>
        <a-form-item label="疾病类型" :label-col="{ span: labelCol.span }" :wrapper-col="{ span: wrapperCol.span }">
          <a-select placeholder="请选择疾病类型" v-decorator="['type_illness', {rules: [{required: true, message: '请选择疾病类型'}]}]">
            <a-select-option v-for="(item,i) in illnessSelect" :key="i" :value="item.id">{{ item.tag }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="病例报告" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-upload
            list-type="picture-card"
            :file-list="fileList"
            @preview="handlePreview"
            @change="handleChange"
            :beforeUpload="beforeUpload"
            :customRequest="onUpload"
            name="iFile"
            v-decorator="['case']"
          >
            <div v-if="fileList.length < 8">
              <a-icon type="plus" />
              <div class="ant-upload-text">
                Upload
              </div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
        </a-form-item>
        <a-form-item label="备注" :label-col="{ span: labelCol.span }" :wrapper-col="{ span: wrapperCol.span }">
          <a-textarea
            placeholder="请输入建议"
            :auto-size="{ minRows: 4, maxRows: 6 }"
            v-decorator="['remark', { rules: [{ required: true, message: '请输入建议' }] }]"
          />
        </a-form-item>

        <a-form-item :wrapper-col="{ span: wrapperCol.span, offset: labelCol.span }">
          <a-button type="primary" html-type="submit">提交</a-button>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-card>
</template>

<script>
import pick from 'lodash.pick'
import * as Api from '@/api/project/patient'
import { SelectRegion } from '@/components'
import * as UploadApi from '@/api/upload'

function getBase64 (file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}

export default {
  components: {
    SelectRegion
  },
  data () {
    return {
      // 标签布局属性
      labelCol: { span: 3 },
      // 输入框布局属性
      wrapperCol: { span: 7 },
      // loading状态
      isLoading: false,
      // 当前表单元素
      form: this.$form.createForm(this),
      // 当前记录详情
      record: {},
      //
      address: [1, 2, 3],

      // 上传中的文件
      uploading: [],
      uploadFile: [],
      previewVisible: false,
      previewImage: '',
      // 疾病选择列
      illnessSelect: [],
      fileList: [
        /* {
          uid: '-1',
          name: 'image.png',
          status: 'done',
          url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
        },
        {
          uid: '-2',
          name: 'image.png',
          status: 'error'
        } */
      ]
    }
  },
  // 初始化数据
  created () {
    // 获取当前详情记录
    this.illnessList()
  },
  methods: {
    // 取消预览
    handleCancel () {
      this.previewVisible = false
    },
    // 图片预览
    async handlePreview (file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    // 设置fileList 值
    setFileList () {
      this.$nextTick(() => {
        this.form.setFieldsValue({ case: JSON.stringify(this.fileList) })
      })
    },
    handleChange ({ fileList }) {
      for (var i = 0; i < this.fileList.length; i++) {
        const file = this.fileList[i]
        if (file.status === 'removed') {
          this.fileList.splice(i, 1)
          this.setFileList()
        }
      }
    },
    // 事件: 上传文件之前
    beforeUpload (file, fileList) {
      const isLt1M = file.size / 1024 / 1024 < 10
      if (!isLt1M) {
        this.$message.error('文件大小不能超出1MB')
        return false
      }
      return true
    },
    // 上传图片
    onUpload (info) {
      const that = this
      this.isLoading = true
      // 记录上传状态
      this.uploading.push(true)
      const beforeUploadCount = this.uploading.length
      // 构建上传参数
      const formData = new FormData()
      formData.append('iFile', info.file)
      formData.append('groupId', 0)
      // 开始上传
      UploadApi.image(formData)
        .then(result => {
          if (result.status === 200) {
            const fileInfo = result.data.fileInfo
            if (beforeUploadCount === this.uploading.length) {
              this.uploading = []
              // this.handleRefresh(true)
              that.fileList.push(
                {
                  uid: fileInfo.file_id,
                  name: fileInfo.file_name,
                  status: 'done',
                  url: fileInfo.preview_url
                }
              )
              that.setFileList()
            }
          } else {
            that.fileList.push(
              {
                uid: '-2',
                name: 'image.png',
                status: 'error'
              }
            )
          }
        }).finally(result => {
        this.isLoading = false
      })
    },

    // 获取当前详情记录
    illnessList () {
      const that = this
      this.isLoading = true
      Api.illnessList()
        .then(result => {
          // 当前记录
          that.illnessSelect = result.data.list.data
          // 设置默认值
          this.setFieldsValue()
        })
        .finally(result => {
          this.isLoading = false
        })
    },

    /**
     * 设置默认值
     */
    setFieldsValue () {
      const { record, $nextTick, form: { setFieldsValue } } = this
      $nextTick(() => {
        setFieldsValue(pick(record, ['tag']))
      })
    },

    /**
     * 确认按钮
     */
    handleSubmit (e) {
      e.preventDefault()
      // 表单验证
      const { form: { validateFields } } = this
      validateFields((errors, values) => {
        // 提交到后端api
        !errors && this.onFormSubmit(values)
      })
    },

    /**
     * 提交到后端api
     */
    onFormSubmit (values) {
      this.isLoading = true
      Api.add({ form: values })
        .then((result) => {
          // 显示提示信息
          this.$message.success(result.message, 1.5, () => {
            this.$router.push('/project/manage/patient_index')
          })
        })
        .finally((result) => {
          this.isLoading = false
        })
    }

  }
}
</script>
<style lang="less" scoped>
.ant-form-item {
  .ant-form-item {
    margin-bottom: 0;
  }
}

/deep/.ant-form-item-control {
  padding-left: 10px;
  .ant-form-item-control {
    padding-left: 0;
  }
}
</style>
